﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LockCrypt.Core;

namespace LockCrypt.DAL {
    /// <summary>
    /// Configuration manager for LockCrypt data layer
    /// </summary>
    public static class DalConfigurationManager {
        private static IDbProvider _provider;
        /// <summary>
        /// Gets or sets the database provider.
        /// </summary>
        /// <value>The database provider.</value>
        public static IDbProvider Provider { 
            get {
                if(_provider == null) {
                    _provider = new NullDbProvider();
                }
                return _provider;
            }
            set { _provider = value; }
        }

        public static void Configure(IDalConfiguration configuration) {
            Provider = configuration.Provider;
        }

        /// <summary>
        /// Gets a database provider.
        /// </summary>
        /// <param name="databasePath">The database path.</param>
        /// <param name="databaseType">Type of the database.</param>
        /// <param name="encryptionAlgorithm">The encryption algorithm.</param>
        /// <param name="password">The password (can be <c>null</c>).</param>
        /// <returns>A provider which can access the specified database.</returns>
        public static IDbProvider GetProvider(string databasePath, Constants.DatabaseType databaseType, EncryptionProviders encryptionAlgorithm, string password) {
            string dbPath = databasePath;
            IEncryptionService encryptionService;
            try {
                switch(encryptionAlgorithm) {
                    case EncryptionProviders.Aes256:
                        encryptionService = new Aes256EncryptionService();
                        break;
                    case EncryptionProviders.None:
                    default:
                        encryptionService = new NullEncryptionService();
                        break;
                }
            } catch {
                encryptionService = new NullEncryptionService();
            }
            IDbProvider provider = new XmlProvider(dbPath, encryptionService);
            return provider;
        }
    }

    /// <summary>
    /// Contains database configuration data.
    /// </summary>
    public interface IDalConfiguration {
        /// <summary>
        /// Gets or sets the database provider.
        /// </summary>
        /// <value>The database provider.</value>
        IDbProvider Provider { get; set; }
    }
}
